import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;

public class PlayParser extends Parser
{
    static HashSet<String> allBatters = new HashSet<String>();
    static HashSet<String> allPitchers = new HashSet<String>();
    
    public static void printAllBatters(String file) throws IOException
    {
        BufferedWriter wri = new BufferedWriter(new FileWriter(file));
        for (String batter : allBatters)
        {
            wri.write("INSERT INTO Batters (Playerid, avg) VALUES ('" + batter + "', NULL);\n");
        }
        wri.close();
    }
    
    public static void printAllPitchers(String file) throws IOException
    {
        BufferedWriter wri = new BufferedWriter(new FileWriter(file));
        for (String pitcher : allPitchers)
        {
            wri.write("INSERT INTO Pitchers (Playerid, ERA) VALUES ('" + pitcher + "', NULL);\n");
        }
        wri.close();
    }

    public PlayParser(String file) throws IOException
    {
        super(file);
    }

    @Override
    public void parse() throws IOException
    {
        String line;
        String gameid = null;
        String homepitcher = null, awaypitcher = null;
        int playid = 1;
        while ((line = reader.readLine()) != null)
        {
            String fields[] = line.split(",");

            if (line.startsWith("id"))
            {
                gameid = line.substring(3);
                playid = 1;
            }
            else if ((line.startsWith("start") || line.startsWith("sub")) && fields[5].equals("1"))
            {
                if (fields[3].equals("0"))
                    awaypitcher = fields[1];
                else
                    homepitcher = fields[1];
            }
            else if (line.startsWith("play") && !fields[6].equals("NP"))
            {
                String batter = fields[3];
                String playtype = fields[6];
                int result = 3;
                if (playtype.startsWith("HR")
                        || playtype.startsWith("S")
                        || playtype.startsWith("D")
                        || playtype.startsWith("T"))
                {
                    result = 1;
                }
                else if (Character.isDigit(playtype.charAt(0)) || playtype.charAt(0) == 'K')
                {
                    result = 2;
                }
                String pitcher = fields[2].equals("0") ? homepitcher : awaypitcher;
                writer.write("INSERT INTO Plays (Gid, Playid, result, pitcher, batter) VALUES ('" + gameid + "', " + playid + ", " + result + ", '"
                        + pitcher + "', '" + batter + "');\n");
                allBatters.add(batter);
                allPitchers.add(pitcher);
                playid++;
            }
        }
        reader.close();
        writer.close();
    }

}
